<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="设备名称" prop="sbName">
        <el-input size="mini"
                  v-model="queryParams.sbName"
                  placeholder="请输入设备名称"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出厂编号" prop="ccBh">
        <el-input size="mini"
                  v-model="queryParams.ccBh"
                  placeholder="请输入出厂编号"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="自编号" prop="zbh">
        <el-input size="mini"
                  v-model="queryParams.zbh"
                  placeholder="请输入自编号"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固定资产编号" prop="gdZcBh">
        <el-input size="mini"
          v-model="queryParams.gdZcBh"
          placeholder="请输入固定资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="校准周期" prop="jzZq">
        <el-input size="mini"
                  v-model="queryParams.jzZq"
                  placeholder="请输入校准周期"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="ggXh">
        <el-input size="mini"
                  v-model="queryParams.ggXh"
                  placeholder="请输入规格型号"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在项目" prop="szXm">
        <el-input size="mini"
                  v-model="queryParams.szXm"
                  placeholder="请输入所在项目"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="sbLx">
        <el-select size="mini" v-model="queryParams.sbLx" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="dict in dict.type.sbgl_sblx"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效期至">
        <el-date-picker size="mini"
                        v-model="daterangeYxqZ"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="设备状态" prop="sbZt">
        <el-select size="mini" v-model="queryParams.sbZt" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in dict.type.sbgl_sbzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sbgl:sbxxgl:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sbgl:sbxxgl:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sbgl:sbxxgl:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sbgl:sbxxgl:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['sbgl:sbxxgl:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          :disabled="!selectedRow || (selectedRow.sbZt !== '正常使用')"
          @click="sbTy"
        >设备停用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          :disabled="!selectedRow || (selectedRow.sbZt !== '停用')"
          @click="sbQy"
        >设备启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          :disabled="!selectedRow || (selectedRow.sbZt !== '正常使用' && selectedRow.sbZt !== '停用')"
          @click="sbBf"
        >设备报废
        </el-button>
      </el-col>
      <span style="color: red">tips: 表格中点击设备名称可查看设备详情信息</span>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table height="60vh" @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="sbxxglList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="设备状态" align="center" prop="sbZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sbgl_sbzt" :value="scope.row.sbZt"/>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="sbName" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link style="font-weight: 600" type="primary">{{ scope.row.sbName }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center">
        <template slot-scope="scope">
          <div>
            <ImagePreviewBase64 :content="scope.row.sbxxglId + ':sbm'"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="出厂编号" align="center" prop="ccBh" show-overflow-tooltip/>
      <el-table-column label="自编号" align="center" prop="zbh" show-overflow-tooltip/>
      <el-table-column label="固定资产编号" align="center" prop="gdZcBh" show-overflow-tooltip/>
      <el-table-column label="校准周期" align="center" prop="jzZq" show-overflow-tooltip/>
      <el-table-column label="规格型号" align="center" prop="ggXh" show-overflow-tooltip/>
      <el-table-column label="准确度/不准确度" align="center" prop="zqdBzqd" show-overflow-tooltip/>
      <el-table-column label="所在项目" align="center" prop="szXm" show-overflow-tooltip/>
      <el-table-column label="单位" align="center" prop="dw" show-overflow-tooltip/>
      <el-table-column label="生产厂家" align="center" prop="scCj" show-overflow-tooltip/>
      <el-table-column label="设备类型" align="center" prop="sbLx" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sbgl_sblx" :value="scope.row.sbLx"/>
        </template>
      </el-table-column>
      <el-table-column label="测量范围" align="center" prop="clFw" show-overflow-tooltip/>
      <el-table-column label="有效期至" align="center" prop="yxqZ" width="110" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.yxqZ, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="购置日期" align="center" prop="gzRq" width="110" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gzRq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="设备备注" align="center" prop="sbBz"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sbgl:sbxxgl:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sbgl:sbxxgl:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-containers" v-show="total > 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改设备信息管理对话框 -->
    <vxe-modal :title="title" v-model="open" width="60%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="130px">
        <el-tabs type="border-card" v-model="activeName">
          <!-- 基本资料 -->
          <el-tab-pane name="jbzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 基本资料</span>
            <div v-if="activeName === 'jbzl'" style="height: 55vh; overflow-y: auto;">
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">基本资料</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="设备名称" prop="sbName">
                      <el-input v-model="form.sbName" placeholder="请输入设备名称"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出厂编号" prop="ccBh">
                      <el-input v-model="form.ccBh" placeholder="请输入出厂编号"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="自编号" prop="zbh">
                      <el-input v-model="form.zbh" placeholder="请输入自编号"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                  <el-form-item label="固定资产编号" prop="gdZcBh">
                    <el-input v-model="form.gdZcBh" placeholder="请输入固定资产编号" />
                  </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="校准周期" prop="jzZq">
                      <el-input v-model="form.jzZq" placeholder="请输入校准周期"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="规格型号" prop="ggXh">
                      <el-input v-model="form.ggXh" placeholder="请输入规格型号"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="准确度/不准确度" prop="zqdBzqd">
                      <el-input v-model="form.zqdBzqd" placeholder="请输入准确度/不准确度"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所在项目" prop="szXm">
<!--                      <el-input v-model="form.szXm" placeholder="请输入所在项目"/>-->
                      <el-select filterable v-model="form.szXm" placeholder="请选择所在项目" style="width: 100%">
                        <el-option
                          v-for="item in szXmList"
                          :key="item.xmxxglId"
                          :label="item.xmName"
                          :value="item.xmName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="单位" prop="dw">
                      <el-select v-model="form.dw" placeholder="请选择单位">
                        <el-option
                          v-for="dict in dict.type.sbgl_sbdw"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="生产厂家" prop="scCj">
<!--                      <el-input v-model="form.scCj" placeholder="请输入生产厂家"/>-->
                      <el-select filterable v-model="form.scCj" placeholder="请选择生产厂家" style="width: 100%">
                        <el-option
                          v-for="item in cjList"
                          :key="item.cjxxglId"
                          :label="item.xmName"
                          :value="item.xmName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="设备类型" prop="sbLx">
                    <el-select v-model="form.sbLx" placeholder="请选择设备类型">
                      <el-option
                        v-for="dict in dict.type.sbgl_sblx"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="测量范围" prop="clFw">
                  <el-input v-model="form.clFw" placeholder="请输入测量范围"/>
                </el-form-item>
                </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="有效期至" prop="yxqZ">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.yxqZ"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择有效期至">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="购置日期" prop="gzRq">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.gzRq"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择购置日期">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="设备备注" prop="sbBz">
                  <el-input type="textarea" :rows="2" v-model="form.sbBz" placeholder="请输入设备备注"/>
                </el-form-item>

              </el-card>
            </div>
          </el-tab-pane>

          <!-- 附件资料 -->
          <el-tab-pane name="fjzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 附件资料</span>
            <div v-if="activeName === 'fjzl'" style="height: 55vh; overflow-y: auto;">
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">附件资料</span>
                </div>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <!-- 上传按钮 -->
                    <el-button size="mini" icon="el-icon-upload" type="primary" @click="SbXxGlFjUpload">上传</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSbxxglFj">删除
                    </el-button>
                  </el-col>
                </el-row>
                <el-table height="40vh" :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                          :data="sbxxglFjList" :row-class-name="rowSbxxglFjIndex"
                          @selection-change="handleSbxxglFjSelectionChange" ref="sbxxglFj">
                  <el-table-column type="selection" width="50" align="center"/>
                  <el-table-column label="序号" prop="index" width="50" align="center"/>
                  <el-table-column label="文件名称" prop="fileName" :formatter="getFileNames" align="center"/>
                  <el-table-column label="文件大小" prop="fileSize" align="center"/>
                  <el-table-column label="操作" align="center" width="150">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handlePreview(scope.row)"
                      >预览
                      </el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-download"
                        @click="handleDownload(scope.row)"
                      >下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 设备信息管理附件上传弹窗 -->
    <vxe-modal title="附件上传" v-model="fjUpload" width="25%" showFooter show-zoom resize @close="fjClose">
      <el-upload
        align="center"
        class="upload-demo"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="20"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        ref="fileUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          请上传
          <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
        </el-button>
        <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
        </el-button>
      </div>

    </vxe-modal>

    <!-- 预览组件 -->
    <KkFileView ref="preview"/>

    <!-- 导入对话框 -->
    <vxe-modal :title="upload.title" v-model="upload.open" width="400px" showFooter show-zoom resize>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 设备详情 -->
    <SbXq ref="sbXq"/>
  </div>
</template>

<script>
import {
  addSbxxgl, deleteSbFj,
  delSbxxgl,
  getSbxxgl,
  getSbXxId,
  insertSbXxGlFjBysbxxglId,
  listSbxxgl, selectSbXxGlFjList,
  updateSbxxgl
} from "@/api/sbgl/sbxxgl";
import {getToken} from "@/utils/auth";
import KkFileView from "@/views/components/KKFileView/kkFileView";
import {selectXmList} from "@/api/sbgl/xmxxgl";
import {selectCjList} from "@/api/sbgl/cjxxgl";
import ImagePreviewBase64 from "@/components/ImagePreviewBase64";
import SbXq from "@/views/sbgl/sbxxgl/components/SbXq";

export default {
  name: "Sbxxgl",
  components: {SbXq, ImagePreviewBase64, KkFileView},
  dicts: ['sbgl_sblx', 'sbgl_sbdw', 'sbgl_sbzt'],
  data() {
    return {
      cjList: [], //厂家列表
      szXmList: [], //所在项目(项目列表)
      xg: false, //判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, //附件上传弹窗
      //要修改的 设备信息管理id
      sbxxglIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      getSbXxId: null, //从后端获取的主键ID
      activeName: 'jbzl',
      selectedRow: null, //当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSbxxglFj: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息管理表格数据
      sbxxglList: [],
      // 设备信息管理附件表格数据
      sbxxglFjList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文件大小时间范围
      daterangeYxqZ: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        idWhere: null,
        sbName: null,
        ccBh: null,
        zbh: null,
        jzZq: null,
        ggXh: null,
        szXm: null,
        sbLx: null,
        yxqZ: null,
        userId: null,
        deptId: null,
        gdZcBh: null,
        sbZt: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sbName: [{required: true, message: "设备名称不能为空", trigger: "blur"}],
        ccBh: [{required: true, message: "出厂编号不能为空", trigger: "blur"}],
        zbh: [{required: true, message: "自编号不能为空", trigger: "blur"}],
        jzZq: [{required: true, message: "校准周期不能为空", trigger: "blur"}],
        ggXh: [{required: true, message: "规格型号不能为空", trigger: "blur"}],
        zqdBzqd: [{required: true, message: "准确度/不准确度不能为空", trigger: "blur"}],
        szXm: [{required: true, message: "所在项目不能为空", trigger: "blur"}],
        dw: [{required: true, message: "单位不能为空", trigger: "blur"}],
        scCj: [{required: true, message: "生产厂家不能为空", trigger: "blur"}],
        sbLx: [{required: true, message: "设备类型不能为空", trigger: "change"}],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sbgl/sbxxgl/importData"
      },

    };
  },
  created() {
    this.getList();
    this.selectSzXm()
  },
  methods: {
    // 查询设备详情信息
    handleButtonClick(row) {
      this.$refs.sbXq.handleOpen(row);
    },
    selectSzXm() {
      //不分页查询项目列表
      selectXmList().then(res => {
        this.szXmList = res.data
      })
      //不分页查询厂家列表
      selectCjList().then(res => {
        this.cjList = res.data
      })
    },
    // 打开预览组件
    handlePreview(row) {
      this.$refs.preview.handleOpen(row);
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    //上传文件之前的钩子
    handleBeforeUpload(file) {
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let xzItemFile = {
          "sbxxglId": that.getSbXxId,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        let xgItemFile = {
          "sbxxglId": that.sbxxglIdEdit,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        if (this.xg === false) {
          // 点击新增按钮的上传
          insertSbXxGlFjBysbxxglId(xzItemFile).then(resFil => {
            that.getSbXxGlFjList();
          })
        } else if (this.xg === true) {
          // 点击修改按钮的上传
          insertSbXxGlFjBysbxxglId(xgItemFile).then(resFil => {
            that.getSbXxGlFjList();
          })
        }
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess("上传成功")
      // this.fjShangChuan = false
    },
    getSbXxGlFjList() {
      let that = this;
      if (this.xg === false) {
        //点击新增 上传文件后的文件列表
        selectSbXxGlFjList(that.getSbXxId).then(resFileList => {
          that.sbxxglFjList = resFileList.data;
        })
      } else {
        //点击修改 上传文件后的文件列表
        selectSbXxGlFjList(that.sbxxglIdEdit).then(resFileList => {
          that.sbxxglFjList = resFileList.data;
        })
      }
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.fileList = this.fileList.map(item => {
          // 使用split方法去除name中的特定前缀
          item.name = item.name.split('/').pop();
          return item;
        });
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    //设备信息管理附件上传按钮
    SbXxGlFjUpload() {
      this.fjUpload = true;
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询设备信息管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeYxqZ && '' != this.daterangeYxqZ) {
        this.queryParams.params["beginYxqZ"] = this.daterangeYxqZ[0];
        this.queryParams.params["endYxqZ"] = this.daterangeYxqZ[1];
      }
      listSbxxgl(this.queryParams).then(response => {
        this.sbxxglList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sbxxglId: this.getSbXxId,
        idWhere: null,
        sbName: null,
        ccBh: null,
        zbh: null,
        gdZcBh: null,
        jzZq: null,
        ggXh: null,
        zqdBzqd: null,
        szXm: null,
        dw: null,
        scCj: null,
        sbLx: null,
        clFw: null,
        yxqZ: null,
        gzRq: null,
        sbBz: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.sbxxglFjList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeYxqZ = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let ids = selection.map(item => item.sbxxglId)
      if (ids.length === 1) {
        this.ids = ids[0]
      }else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //设备停用
    sbTy(row) {
      const sbxxglId = row.sbxxglId || this.ids
      getSbxxgl(sbxxglId).then(response => {
        this.form = response.data;
        this.sbxxglFjList = response.data.sbxxglFjList;
      });

      this.$confirm('确认要把设备名称为:' + this.selectedRow.sbName + '设备自编号为:' + this.selectedRow.zbh + '的设备停用吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.sbZt = '停用'
        updateSbxxgl(this.form).then(response => {
          this.$modal.msgSuccess("设备已停用");
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消停用'
        });
      });
    },
    //设备启用
    sbQy(row) {
      const sbxxglId = row.sbxxglId || this.ids
      getSbxxgl(sbxxglId).then(response => {
        this.form = response.data;
        this.sbxxglFjList = response.data.sbxxglFjList;
      });

      this.$confirm('确认要把设备名称为:' + this.selectedRow.sbName + '设备自编号为:' + this.selectedRow.zbh + '的设备启用吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.sbZt = '正常使用'
        updateSbxxgl(this.form).then(response => {
          this.$modal.msgSuccess("设备已启用");
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消启用'
        });
      });
    },
    //设备报废
    sbBf(row) {
      const sbxxglId = row.sbxxglId || this.ids
      getSbxxgl(sbxxglId).then(response => {
        this.form = response.data;
        this.sbxxglFjList = response.data.sbxxglFjList;
      });

      this.$confirm('确认要把设备名称为:' + this.selectedRow.sbName + '设备自编号为:' + this.selectedRow.zbh + '的设备报废吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.sbZt = '报废'
        updateSbxxgl(this.form).then(response => {
          this.$modal.msgSuccess("设备已报废");
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消报废'
        });
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.xg = false
      getSbXxId().then(res => {
        this.getSbXxId = res.msg
        this.reset();
      })
      this.activeName = 'jbzl'
      this.open = true;
      this.title = "添加设备信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.xg = true
      const sbxxglId = row.sbxxglId || this.ids
      this.sbxxglIdEdit = row.sbxxglId || this.ids
      getSbxxgl(sbxxglId).then(response => {
        this.form = response.data;
        this.sbxxglFjList = response.data.sbxxglFjList;
        this.activeName = 'jbzl'
        this.open = true;
        this.title = "修改设备信息管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.sbxxglFjList = this.sbxxglFjList;
          if (this.form.idWhere != null) {
            updateSbxxgl(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.xg = false
            });
          } else {
            addSbxxgl(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sbxxglIds = row.sbxxglId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delSbxxgl(sbxxglIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 设备信息管理附件序号 */
    rowSbxxglFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 设备信息管理附件删除按钮操作 */
    handleDeleteSbxxglFj() {
      if (this.checkedSbxxglFj.length == 0) {
        this.$modal.msgError("请先选择要删除的设备信息管理附件数据");
      } else {
        const fjIds = this.checkedSbxxglFj;
        this.$modal.confirm('确定删除选中记录？').then(function() {
          return deleteSbFj(fjIds);
        }).then(() => {
          getSbxxgl(this.sbxxglIdEdit).then(response => {
            this.sbxxglFjList = response.data.sbxxglFjList;
          });
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 复选框选中数据 */
    handleSbxxglFjSelectionChange(selection) {
      this.checkedSbxxglFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sbgl/sbxxgl/export', {
        ...this.queryParams
      }, `sbxxgl_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('sbgl/sbxxgl/importTemplate', {
      }, `template_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备信息管理导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      // 打开遮罩层
      this.$modal.loading("正在导入数据，请稍后...");
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      // 关闭遮罩层
      this.$modal.closeLoading();
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }

  }
};
</script>
